<template>
  <div class="container">
    <div class="table_container">
      <div class="table_content">
        <div class="title">
          <el-button type="primary" @click="dialogVisibleAccount = true" round>新增账号</el-button>
          <el-button id="btndel" type="danger" round @click="handleBatchDelete">批量删除</el-button>

          <!-- 搜索区域 -->
          <div class="search-container">
            <el-input
                v-model="searchKeyword"
                placeholder="搜索账户名称或所属角色"
                clearable
                @clear="handleSearchClear"
                @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button @click="handleSearch" :icon="Search" />
              </template>
            </el-input>
          </div>
        </div>
        <div class="table">
          <el-table class="table-tab" :data="filteredUsers" height="70vh" border
                    @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="序号" type="index" width="60vh" align="center">
              <template #default="scope">
                <span v-text="getIndex(scope.$index)"></span>
              </template>
            </el-table-column>
            <el-table-column prop="userName" label="账户名称" width="250" align="center" />
            <el-table-column prop="userCode" label="所属角色" width="250" align="center" />
            <el-table-column prop="loginDate" label="创建时间" width="300" align="center" />
            <el-table-column label="操作" align="center" width="230">
              <template #default="scope">
                <el-button key="primary" type="primary" @click="handleEdit(scope.$index, scope.row)" link>
                  修改
                </el-button>
                <el-button key="danger" type="danger" @click="handleDelete(scope.$index, scope.row)" link>
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination-block">
          <el-pagination v-model:current-page="user_data.pageIndex" v-model:page-size="user_data.pageSize"
                         :page-sizes="pageSizes" :small="small" :disabled="disabled" :background="background"
                         layout="total, sizes, prev, pager, next, jumper" :total="user_data.total"
                         @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>
      <!-- 新增AccountDialog -->
      <el-dialog v-model="dialogVisibleAccount" title="新增账号" width="40%" :before-close="handleClose">
        <el-form :model="form_data" :rules="userRules" label-width="120px">
          <el-form-item prop="userName" label="账号名称">
            <el-input v-model="form_data.userName" />
          </el-form-item>
          <el-form-item prop="password" label="账号密码">
            <el-input v-model="form_data.password" type="password" />
          </el-form-item>
          <el-form-item prop="repassword" label="确认密码">
            <el-input v-model="form_data.repassword" type="password" />
          </el-form-item>
          <el-form-item label="所属角色">
            <el-select v-model="form_data.AdminUser" placeholder="请选择">
              <el-option label="管理员" value="admin" />
              <el-option label="普通用户" value="user" />
            </el-select>
          </el-form-item>
          <el-form-item class="dialog-btn">
            <el-button type="primary" @click="onSubmit">确认</el-button>
            <el-button @click="dialogVisibleAccount = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

      <!-- 修改用户信息的dialog -->
      <el-dialog v-model="dialogEditUser" title="修改账号" width="40%" :before-close="handleClose">
        <el-form :model="edit_form_data" :rules="userRules" label-width="120px">
          <el-form-item prop="userName" label="账号名称">
            <el-input v-model="edit_form_data.userName" />
          </el-form-item>
          <el-form-item prop="password" label="账号密码">
            <el-input v-model="edit_form_data.password" type="password" />
          </el-form-item>
          <el-form-item prop="repassword" label="确认密码">
            <el-input v-model="edit_form_data.repassword" type="password" />
          </el-form-item>
          <el-form-item label="所属角色">
            <el-select v-model="edit_form_data.AdminUser" placeholder="请选择">
              <el-option label="管理员" value="admin" />
              <el-option label="普通用户" value="user" />
            </el-select>
          </el-form-item>
          <el-form-item class="dialog-btn">
            <el-button type="primary" @click="editSubmit">确认</el-button>
            <el-button @click="dialogEditUser = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

      <!-- 删除用户信息的dialog -->
      <el-dialog v-model="deleteUserVisible" title="删除用户" width="320">
        <div class="delete-confirm">
          <el-icon color="#F56C6C" size="24px"><Warning /></el-icon>
          <div class="confirm-text">
            确认删除用户 <strong>{{ remove_user.userName }}</strong> 吗？
          </div>
          <div class="confirm-hint">
            此操作将永久删除该用户信息，且不可恢复
          </div>
          <el-input
              v-model="input_delete_data"
              placeholder="请输入：确认删除"
              class="custom-input"
          />
        </div>
        <template #footer>
                <span class="dialog-footer">
                    <el-button @click="deleteUserVisible = false">取消</el-button>
                    <el-button type="danger" @click="deleteUser">确认</el-button>
                </span>
        </template>
      </el-dialog>

      <!-- 批量删除确认对话框 -->
      <el-dialog v-model="batchDeleteVisible" title="批量删除用户" width="320">
        <div class="batch-delete-confirm">
          <el-icon color="#F56C6C" size="24px"><Warning /></el-icon>
          <div class="confirm-text">
            确认删除选中的 <strong>{{ selectedUsers.length }}</strong> 个用户吗？
          </div>
          <div class="confirm-hint">
            此操作将永久删除这些用户信息，且不可恢复
          </div>
          <el-input
              v-model="batchInputDeleteData"
              placeholder="请输入：确认删除"
              class="custom-input"
          />
        </div>
        <template #footer>
                <span class="dialog-footer">
                    <el-button @click="batchDeleteVisible = false">取消</el-button>
                    <el-button type="danger" @click="confirmBatchDelete">确认</el-button>
                </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Warning } from '@element-plus/icons-vue'

// 设置分页数据数
let pageSizes = ref([1, 5, 8, 10])
// 增加区域dialog
const dialogVisibleAccount = ref(false);
// 删除用户dialog框
const deleteUserVisible = ref(false)
// 修改用户dialog框
const dialogEditUser = ref(false)
// 确认删除框
const input_delete_data = ref('')
// 批量删除对话框
const batchDeleteVisible = ref(false)
// 批量删除确认输入
const batchInputDeleteData = ref('')
// 选中的用户数据
const selectedUsers = ref([])
// 搜索关键词
const searchKeyword = ref('')

// 检查表单项是否有空
const checkFormFields = (form) => {
  for (const key in form) {
    if (form[key] === "" || form[key] === undefined || form[key] === null) {
      return false; // 如果有空字段，返回 false
    }
  }
  return true; // 所有字段都已填写
};

// 从localStorage获取用户数据或使用默认数据
const getUsersFromStorage = () => {
  const storedUsers = localStorage.getItem('userManagementData')
  if (storedUsers) {
    return JSON.parse(storedUsers)
  }
  // 默认数据
  return [
    { rowID: 1, userName: 'admin', userCode: '管理员', loginDate: '2024-01-01 10:00:00' },
    { rowID: 2, userName: 'user1', userCode: '普通用户', loginDate: '2024-02-15 14:30:00' },
    { rowID: 3, userName: 'user2', userCode: '普通用户', loginDate: '2024-03-20 09:15:00' },
    { rowID: 4, userName: 'test', userCode: '管理员', loginDate: '2025-01-12 16:45:00' },
    { rowID: 5, userName: 'demo', userCode: '普通用户', loginDate: '2025-02-14 11:20:00' },
    { rowID: 6, userName: 'dev', userCode: '管理员', loginDate: '2025-02-14 13:10:00' },
    { rowID: 7, userName: 'guest', userCode: '普通用户', loginDate: '2025-02-22 08:30:00' },
    { rowID: 8, userName: 'operator', userCode: '管理员', loginDate: '2025-03-11 15:45:00' },
    { rowID: 9, userName: 'viewer', userCode: '普通用户', loginDate: '2025-03-20 10:20:00' },
    { rowID: 10, userName: 'editor', userCode: '管理员', loginDate: '2025-03-28 14:15:00' }
  ]
}

// 保存用户数据到localStorage
const saveUsersToStorage = (users) => {
  localStorage.setItem('userManagementData', JSON.stringify(users))
}

// 用户加分页数据
const user_data = reactive({
  tableData: [],  // 表格数据
  pageIndex: 1,  // 默认第一页
  total: 0,      // 数据总数
  pageSize: 10,     // 默认每页显示10条
})

// 定义表单规则
const userRules = reactive({
  userName: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 3, max: 10, message: '长度在3到10个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
  ],
  repassword: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
  ]
});

// 增加账号
const form_data = reactive({
  userName: '',
  password: '',
  repassword: '',
  AdminUser: ''
});

// 修改账号
const edit_form_data = reactive({
  rowID: '',      // 需要id确认是否存在此账号
  userName: '',
  password: '',
  repassword: '',
  AdminUser: ''
});

// 获取表格序号
const getIndex = (index) => {
  return (user_data.pageIndex - 1) * user_data.pageSize + index + 1;
}

// 点击删除获取用户信息值
let remove_user = reactive({
  id: null,
  userName: null
})

// 点击删除用户信息按钮
const handleDelete = (index, row) => {
  // 获取所选择删除用户的信息值
  remove_user.id = row.rowID
  remove_user.userName = row.userName
  deleteUserVisible.value = true
}

// 模拟获取用户列表
const get_users = () => {
  const users = getUsersFromStorage()
  // 模拟分页
  const start = (user_data.pageIndex - 1) * user_data.pageSize
  const end = start + user_data.pageSize
  user_data.tableData = users.slice(start, end)
  user_data.total = users.length
}

// 每页大小
const handleSizeChange = (val) => {
  user_data.pageSize = val
  get_users()
}

// 当前页
const handleCurrentChange = (val) => {
  user_data.pageIndex = val
  get_users()
}

// 重置表单
const resetForm = () => {
  form_data.userName = ''
  form_data.password = ''
  form_data.repassword = ''
  form_data.AdminUser = ''
}

// 生成随机ID
const generateId = () => {
  const users = getUsersFromStorage()
  return Math.max(...users.map(user => user.rowID)) + 1
}

// 提交增加用户表单
const onSubmit = () => {
  // 先检查是否有空字段
  if (!checkFormFields(form_data)) {
    ElMessage.error("所有元素必须填写");
    return;
  }
  // 简单验证
  if (form_data.password !== form_data.repassword) {
    ElMessage.error('两次输入的密码不一致')
    return
  }

  const users = getUsersFromStorage()
  // 添加到模拟数据
  const newUser = {
    rowID: generateId(),
    userName: form_data.userName,
    userCode: form_data.AdminUser === 'admin' ? '管理员' : '普通用户',
    loginDate: new Date().toLocaleString()
  }

  users.unshift(newUser) // 添加到数组开头
  saveUsersToStorage(users)
  user_data.total = users.length

  // 重置表单
  resetForm()
  ElMessage.success('用户添加成功')
  dialogVisibleAccount.value = false
  get_users()
}

// 提交修改用户信息表单
const editSubmit = () => {
  // 先检查是否有空字段
  if (!checkFormFields(edit_form_data)) {
    ElMessage.error("所有元素必须填写");
    return;
  }
  // 简单验证
  if (edit_form_data.password !== edit_form_data.repassword) {
    ElMessage.error('两次输入的密码不一致')
    return
  }

  const users = getUsersFromStorage()
  // 更新模拟数据
  const index = users.findIndex(user => user.rowID === edit_form_data.rowID)
  if (index !== -1) {
    users[index].userName = edit_form_data.userName
    users[index].userCode = edit_form_data.AdminUser === 'admin' ? '管理员' : '普通用户'
    saveUsersToStorage(users)

    ElMessage.success('用户信息修改成功')
    dialogEditUser.value = false
    get_users()
  }
}

// 编辑用户信息功能，回显数据
const handleEdit = (index, row) => {
  edit_form_data.rowID = row.rowID
  dialogEditUser.value = true

  const users = getUsersFromStorage()
  // 从模拟数据中查找用户
  const user = users.find(user => user.rowID === row.rowID)
  if (user) {
    edit_form_data.userName = user.userName
    edit_form_data.AdminUser = user.userCode === '管理员' ? 'admin' : 'user'
  }
}

// 点击确认删除用户
const deleteUser = () => {
  if (input_delete_data.value === '确认删除') {
    const users = getUsersFromStorage()
    // 从模拟数据中删除
    const index = users.findIndex(user => user.rowID === remove_user.id)
    if (index !== -1) {
      users.splice(index, 1)
      saveUsersToStorage(users)
      user_data.total = users.length

      ElMessage.success('用户删除成功')
      deleteUserVisible.value = false
      input_delete_data.value = ''
      get_users()
    }
  } else {
    ElMessage.error('请输入"确认删除"以确认操作')
    input_delete_data.value = ''
  }
}

// 处理选中行变化
const handleSelectionChange = (val) => {
  selectedUsers.value = val
}

// 处理批量删除
const handleBatchDelete = () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请先选择要删除的用户')
    return
  }
  batchDeleteVisible.value = true
  batchInputDeleteData.value = ''
}

// 确认批量删除
const confirmBatchDelete = () => {
  if (batchInputDeleteData.value !== '确认删除') {
    ElMessage.error('请输入"确认删除"以确认操作')
    batchInputDeleteData.value = ''
    return
  }

  const users = getUsersFromStorage()
  // 获取所有选中用户的ID
  const selectedIds = selectedUsers.value.map(user => user.rowID)

  // 从模拟数据中删除选中的用户
  for (let i = users.length - 1; i >= 0; i--) {
    if (selectedIds.includes(users[i].rowID)) {
      users.splice(i, 1)
    }
  }

  saveUsersToStorage(users)
  user_data.total = users.length
  selectedUsers.value = []
  batchDeleteVisible.value = false
  batchInputDeleteData.value = ''

  ElMessage.success(`成功删除${selectedIds.length}个用户`)
  get_users()
}

// 搜索处理
const handleSearch = () => {
  user_data.pageIndex = 1
  get_users()
}

// 清除搜索
const handleSearchClear = () => {
  searchKeyword.value = ''
  user_data.pageIndex = 1
  get_users()
}

// 计算属性：过滤用户数据
const filteredUsers = computed(() => {
  if (!searchKeyword.value) return user_data.tableData

  const keyword = searchKeyword.value.toLowerCase()
  return user_data.tableData.filter(user =>
      user.userName.toLowerCase().includes(keyword) ||
      user.userCode.toLowerCase().includes(keyword)
  )
})

onMounted(() => {
  get_users()
})
</script>

<style scoped>
.container {
  padding: 20px;
  background: linear-gradient(135deg, #e0f7fa, #c8e6c9, #a5d6a7);
  min-height: 100vh;
  width: 100%;
}

.table_container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
  width: 80%;
  margin: 0 auto;
}

.table_content {
  padding: 20px;
}

.title {
  display: flex;
  align-items: center;
  padding: 20px;
  gap: 15px;
  flex-wrap: wrap;
}

/* 搜索区域样式 */
.search-container {
  margin-left: auto;
  width: 300px;
}

.table {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.table-tab {
  width: 90%;
  border-radius: 6px;
  overflow: hidden;
  font-size: 15px;
}

.table-tab :deep(.el-table__header) th {
  background-color: #f5f7fa;
  font-weight: 600;
  font-size: 16px;
}

.table-tab :deep(.el-table__row) {
  transition: background-color 0.3s;
}

.table-tab :deep(.el-table__row:hover) {
  background-color: #f5f7fa !important;
}

.pagination-block {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.delete-confirm, .batch-delete-confirm {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  padding: 15px;
}

.confirm-text {
  margin: 15px 0 10px;
  font-size: 16px;
}

.confirm-hint {
  color: #909399;
  font-size: 14px;
  margin-bottom: 15px;
}

.custom-input {
  width: 100%;
}

.dialog-btn {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .search-container {
    margin-left: 0;
    margin-top: 15px;
    width: 100%;
  }
}

@media (max-width: 768px) {
  .title {
    flex-direction: column;
    align-items: stretch;
  }

  .el-button {
    width: 100%;
    margin-bottom: 10px;
  }

  #btndel {
    margin-right: 0;
  }

  .search-container {
    margin-top: 10px;
  }
}
</style>